package com.ruizhong.centercontroll;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import android.graphics.Color;
import android.graphics.SurfaceTexture;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import android.view.LayoutInflater;

import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;

import android.webkit.WebSettings;
import android.webkit.WebView;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;

import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout;

import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;

import com.google.gson.Gson;
import com.ruizhong.centercontroll.util.JsApi;

import com.ruizhong.centercontroll.util.VLCPlayer;
import com.ruizhong.centercontroll.util.ZoomView;


import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;

import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import wendu.dsbridge.DWebView;


public class MainActivity extends AppCompatActivity implements VLCPlayer.VLCPlayerCallback {

    private static List<Map<String, Object>> videoMapList;


    private RelativeLayout fatherRelativeLayout;

    private Double webWinWidth;

    private Double webWinHeight;

    private Integer androidAppWidth;

    private Integer androidAppHeight;

    private Map<String, String> streamMap;

    private String centerServerIp;

    private String token;

    private DWebView webView;

    private static ValueCallback<Uri> uploadMessage;//单选文件回调

    private Map<String, String> conditionMap;

    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    private Map<Integer, Map> oldVlcPlayersMap = new HashMap<>();

    public static ValueCallback<Uri[]> uploadMessageAboveL; //多选文件回调

    private String[] pageNameList;

    private String selectedPage;

    private Integer selectedPageIndex = 0;

    private String pagePrefix = "displayPage";

    private EventManager asr;

    private EventListener listener;

    public static Boolean scalenable = true;

    public static TextureView textureView;

    public static Boolean swipping = false;

    public static long pressStartTime;

    public static String tokenId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);


        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        );
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            centerServerIp = bundle.getString("centerServerIp");
            token = bundle.getString("token");
        }
//        Spinner spinner3 = findViewById(R.id.ModeSpinner);
        getAllPages();
        Spinner spinner = findViewById(R.id.spinner2);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedPageIndex = position;
                selectedPage = pagePrefix + "/" + parent.getItemAtPosition(position) + "/0";
                goToOtherPage();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
//        spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                String mode = parent.getItemAtPosition(position).toString();
//                if (mode.equals("编辑模式")) {
//                    pagePrefix = "editPage";
//                } else {
//                    pagePrefix = "displayPage";
//                }
//                if (pageNameList == null || selectedPageIndex == null) {
//                    return;
//                }
//                selectedPage = pagePrefix + "/" + pageNameList[selectedPageIndex] + "/0";
//                goToOtherPage();
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });
        // 获取屏幕密度
        fatherRelativeLayout = findViewById(R.id.father);
        ViewTreeObserver vto = fatherRelativeLayout.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 获取宽高
                androidAppWidth = fatherRelativeLayout.getWidth();
                androidAppHeight = fatherRelativeLayout.getHeight();

                // 移除监听器，避免多次调用（注意：在API 16及以上需要这样做）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    fatherRelativeLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    // 对于API 16以下的版本，使用removeGlobalOnLayoutListener
                    fatherRelativeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });

        Button startRecordBtn = findViewById(R.id.recognizeAudio);
        webView = findViewById(R.id.webView);

        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
        webView.setWebContentsDebuggingEnabled(true);
        webView.addJavascriptObject(new JsApi(this), null);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
//        WebSettings webSettings = webView.getSettings();
//        webSettings.setJavaScriptEnabled(true);
//        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        webSettings.setDomStorageEnabled(true);
//        webSettings.setDatabaseEnabled(true);
//        webSettings.setAllowFileAccess(true);
//        webSettings.setSavePassword(true);
////      webSettings.setBuiltInZoomControls(true);
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSettings.setUseWideViewPort(true);
//        webSettings.setBlockNetworkImage(false);
//        webSettings.setAppCacheEnabled(true);
//        webSettings.setAllowFileAccess(true);
//        webView.setDefaultHandler(new DefaultHandler());
//        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
//        webView.setWebChromeClient(new WebChromeClient());
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= 19) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;

                openImageChooserActivity(fileChooserParams.getAcceptTypes());

                return true;

            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                System.out.println("加载进度" + newProgress);
                super.onProgressChanged(view, newProgress);
            }
        });
        if (webView != null) {
            SharedPreferences sharedPreferences = getSharedPreferences("singlePageControl", MODE_PRIVATE);
            String originalSelectedLanguage = sharedPreferences.getString("language", null);
            this.backToIndex(null);
        }


        requestPermission();
        asr = EventManagerFactory.create(this, "asr");
        listener = new EventListener() {
            @Override
            public void onEvent(String name, String params, byte[] data, int offset, int length) {
                if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_READY)) {
                    // 引擎就绪，可以说话，一般在收到此事件后通过UI通知用户可以说话了
                    System.out.println("可以开始说话了");
                }
                if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
                    // 识别相关的结果都在这里
                    if (params == null || params.isEmpty()) {
                        return;
                    }
                    if (params.contains("\"final_result\"")) {
                        // 一句话的最终识别结果
                        if (sendToWeb) {
                            Gson gson = new Gson();
                            Map map = gson.fromJson(params, Map.class);
                            String resultsRecognition = map.get("results_recognition").toString();
                            AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
                                    .setIcon(R.mipmap.ic_launcher)
                                    .setTitle("语音识别")
                                    .setMessage("确认执行口令: " + resultsRecognition)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("执行", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            webView.callHandler("sendAudioCommand", new Object[]{resultsRecognition}, null);
                                            dialog.dismiss();
                                        }
                                    }).create();
                            dialog.show();

                        }
                    }

                }
            }
        };
        asr.registerListener(listener);
    }

    private static final String TAG = "centerControllMain";

    private void requestPermission() {
        Log.d(TAG, "requestPermission");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.INTERNET}, 0);
    }

    private boolean sendToWeb = false;

    private boolean speechDialogOpening = false;

    public synchronized void startOrStopAudio(View view) {
        if (speechDialogOpening) {
            return;
        }
        asr.send(SpeechConstant.ASR_START, "{}", null, 0, 0);
        LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_with_progress, null);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("语音识别")
                .setView(dialogView)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sendToWeb = false;
                        asr.send(SpeechConstant.ASR_STOP, "{}", null, 0, 0);
                        dialog.dismiss();
                        speechDialogOpening = false;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sendToWeb = true;
                        asr.send(SpeechConstant.ASR_STOP, "{}", null, 0, 0);
                        dialog.dismiss();
                        speechDialogOpening = false;
                    }
                }).create();
        dialog.show();
        speechDialogOpening = true;
    }

    private Boolean checkedPassword=false;

    private void getAllPages() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String requestUrl = "http://" + centerServerIp + ":8094/page/api/getAllPages";
                try {
                    URL url = new URL(requestUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setRequestProperty("Authorization", token);
                    connection.setRequestProperty("checkedPassword",checkedPassword.toString());
                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) { // success
                        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String inputLine;
                        StringBuilder response = new StringBuilder();

                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();

                        Gson gson = new Gson();
                        Map map = gson.fromJson(response.toString(), Map.class);
                        LinearLayout passwordLayout = findViewById(R.id.passwordLayout);
                        if ((Double) map.get("status") == 402.0) {
                            passwordLayout.setVisibility(View.VISIBLE);
                            Button checkBtn = findViewById(R.id.checkPwd);
                            checkBtn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    EditText passwordInput = findViewById(R.id.passwordInput);
                                    try {

                                        Boolean res = checkPassword(passwordInput.getText().toString());
                                        if (res){
                                            checkedPassword = true;
                                            getAllPages();
                                        }
                                    } catch (IOException | ExecutionException | InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            });
                            return;
                        }
                        checkedPassword = false;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                passwordLayout.setVisibility(View.GONE);
                            }
                        });
                        List<Map<String, String>> pageListMap = (List<Map<String, String>>) map.get("data");
                        pageNameList = new String[pageListMap.size()];
                        for (int i = 0; i < pageListMap.size(); i++) {
                            Map<String, String> pageNameMap = pageListMap.get(i);
                            String pageName = pageNameMap.get("pageName");
                            pageNameList[i] = pageName;
                        }
                        Spinner spinner = findViewById(R.id.spinner2);
//                        Spinner spinner3 = findViewById(R.id.ModeSpinner);
//                        String[] modeArr = {"控制模式", "编辑模式"};
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.support_simple_spinner_dropdown_item, pageNameList) {
                                    @NonNull
                                    @Override
                                    public View getView(int position, @androidx.annotation.Nullable View convertView, @NonNull ViewGroup parent) {
                                        TextView textView = (TextView) super.getView(position, convertView, parent);
                                        textView.setTextSize(16);  // 设置字体字号
                                        textView.setTextColor(Color.rgb(50, 179, 226));  // 设置字体颜色
                                        return textView;
                                    }

                                    @Override
                                    public View getDropDownView(int position, @androidx.annotation.Nullable View convertView, @NonNull ViewGroup parent) {
                                        TextView textView = (TextView) super.getDropDownView(position, convertView, parent);
                                        textView.setTextSize(16);  // 设置字体字号
                                        textView.setTextColor(Color.rgb(50, 179, 226));  // 设置字体颜色
                                        return textView;
                                    }
                                };
                                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                                spinner.setAdapter(adapter);
                                spinner.setSelection(0);

//                                adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, modeArr) {
//                                    @NonNull
//                                    @Override
//                                    public View getView(int position, @androidx.annotation.Nullable View convertView, @NonNull ViewGroup parent) {
//                                        TextView textView = (TextView) super.getView(position, convertView, parent);
//                                        textView.setTextSize(16);  // 设置字体字号
//                                        textView.setPadding(30, 30, 30, 30);
//                                        textView.setTextColor(Color.rgb(50, 179, 226));  // 设置字体颜色
//                                        return textView;
//                                    }
//
//                                    @Override
//                                    public View getDropDownView(int position, @androidx.annotation.Nullable View convertView, @NonNull ViewGroup parent) {
//                                        TextView textView = (TextView) super.getDropDownView(position, convertView, parent);
//                                        textView.setTextSize(16);  // 设置字体字号
//                                        textView.setPadding(30, 30, 30, 30);
//                                        textView.setTextColor(Color.rgb(50, 179, 226));  // 设置字体颜色
//                                        return textView;
//                                    }
//                                };
//                                spinner3.setAdapter(adapter);
                            }
                        });

                    } else {
                        System.out.println("GET request not worked. Response Code: " + responseCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private Boolean checkPassword(String password) throws IOException, ExecutionException, InterruptedException {
        FutureTask<Boolean> futureTask = new FutureTask<>(() -> {
            String url = "http://" + centerServerIp + ":8094/user/api/checkPassword";
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            StringBuilder response = new StringBuilder();

            try {
                // 1. 创建URL对象并打开连接
                URL requestUrl = new URL(url);
                connection = (HttpURLConnection) requestUrl.openConnection();

                // 2. 设置请求方法、头部和输出流
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json; utf-8");
                connection.setRequestProperty("Accept", "application/json");
                connection.setRequestProperty("Authorization", token);
                connection.setRequestProperty("checkedPassword",checkedPassword.toString());
                connection.setDoOutput(true);

                // 3. 构建JSON请求体
                String jsonInputString = "{\"password\":\"" + password + "\"}";

                // 4. 写入请求体
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonInputString.getBytes("utf-8");
                    os.write(input, 0, input.length);
                }

                // 5. 读取响应
                int responseCode = connection.getResponseCode();
                response = null;
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    response = new StringBuilder();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    Gson gson = new Gson();
                    Map map = gson.fromJson(response.toString(), Map.class);
                    System.out.println(map);
                    return (Double)map.get("status") == 200.0;
                } else {
                    throw new IOException("HTTP error code: " + responseCode);
                }
            } catch (ProtocolException e) {
                e.printStackTrace();
                return false;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } finally {
                // 6. 清理资源
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (connection != null) connection.disconnect();
            }
        });
        new Thread(futureTask).start();
        Boolean res = futureTask.get();
        System.out.println(res);
        return res;
    }


    /**
     * 打开文件管理器  选择文件
     */
    private void openImageChooserActivity(String[] acceptType) {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT); //允许用户选择特殊种类的数据，并返回

        //一个布尔型值，声明用户是否可以一次选择多个文件。
        i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        i.addCategory(Intent.CATEGORY_OPENABLE); //增加一个可打开的分类

        i.setType("*/*");

        //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            i.putExtra(Intent.EXTRA_MIME_TYPES,
//                    new String[]{"image/jpeg","image/jpg","image/png","application/pdf"});
                    acceptType);
        }

        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);

    }


    /*
     回调函数？
     在onActivityResult里处理获取到的文件
     重载onActivityResult()方法，在里面接收用户选择的文件的Uri，传给input标签
      */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }

    }

    /*
        android 5.0
        多文件的结果返回处理
         */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        Log.d("test1234", "onActivityResultAboveL");

        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    public void destoryVlcPlayers() {
        if (videoMapList == null || videoMapList.size() == 0) {
            return;
        }
        for (int i = 0; i < videoMapList.size(); i++) {
            Map<String, Object> vlcPlayerMap = oldVlcPlayersMap.get(i);
            clearOldStreamPlayer(vlcPlayerMap);
        }
        conditionMap = null;
        uploadMessageAboveL = null; //多选文件回调
        uploadMessage = null;
        videoMapList = null;
        oldVlcPlayersMap = new HashMap<>();
    }

    private void checkVlcPlayers() {
        if (videoMapList == null) {
            return;
        }
        for (int i = 0; i < videoMapList.size(); i++) {
            Map<String, Object> videoMap = videoMapList.get(i);
            Double videoType = (Double) videoMap.get("videoType");
            if (videoType != 2.0 && videoType != 4.0) {
                videoMap.put("needDraw", Boolean.FALSE);
                continue;
            }
            Boolean conditionShow = (Boolean) videoMap.get("conditionShow");
            Object displayVariableNameObject = videoMap.get("displayVariableName");
            Object displayVariableValueObject = videoMap.get("displayVariableValue");
            String displayVariableName = displayVariableNameObject == null ? null : displayVariableNameObject.toString();
            String displayVariableValue = displayVariableValueObject == null ? null : displayVariableValueObject.toString();
            String value = conditionMap.get(displayVariableName);
            Map<String, Object> vlcPlayerMap = oldVlcPlayersMap.get(i);
            Object needDraw = videoMap.get("needDraw");
            //           检查动态显示与隐藏
            if (conditionShow && (value == null || !value.equals(displayVariableValue))) {
                clearOldStreamPlayer(vlcPlayerMap);
                videoMap.put("needDraw", Boolean.FALSE);
                continue;
            }
            if ((needDraw == null || !(Boolean) needDraw) && conditionShow && (value != null && value.equals(displayVariableValue))) {
                videoMap.put("needDraw", Boolean.TRUE);

            }
            if (vlcPlayerMap == null) {
                videoMap.put("needDraw", Boolean.TRUE);

            }
            if (vlcPlayerMap == null) {
                continue;
            }
            Object realStreamUrlObject = vlcPlayerMap.get("realStreamUrl");
            Object streamVariableObject = videoMap.get("streamVariable");

//            检查流地址是否改变
            String realStreamUrl = realStreamUrlObject == null ? null : realStreamUrlObject.toString();
            String newRealStreamUrl = conditionMap.get(streamVariableObject) == null ? null : conditionMap.get(streamVariableObject).trim();
            if (newRealStreamUrl == null) {
                clearOldStreamPlayer(vlcPlayerMap);
                videoMap.put("needDraw", Boolean.FALSE);
                continue;
            }
            if (realStreamUrl == null || !realStreamUrl.equals(newRealStreamUrl)) {
                clearOldStreamPlayer(vlcPlayerMap);
                videoMap.put("needDraw", Boolean.TRUE);

            }
//            对比大小位置是否改变

            String videoW = String.valueOf(videoMap.get("w"));
            String videoH = String.valueOf(videoMap.get("h"));
            String videoX = String.valueOf(videoMap.get("x"));
            String videoY = String.valueOf(videoMap.get("y"));
            String vlcPlayerMapW = String.valueOf(vlcPlayerMap.get("w"));
            String vlcPlayerMapH = String.valueOf(vlcPlayerMap.get("h"));
            String vlcPlayerMapX = String.valueOf(vlcPlayerMap.get("x"));
            String vlcPlayerMapY = String.valueOf(vlcPlayerMap.get("y"));
            System.out.println(oldVlcPlayersMap);
            if (!videoW.equals(vlcPlayerMapW) || !videoH.equals(vlcPlayerMapH) || !videoX.equals(vlcPlayerMapX) || !videoY.equals(vlcPlayerMapY)) {
                clearOldStreamPlayer(vlcPlayerMap);
                videoMap.put("needDraw", Boolean.TRUE);

            }

        }


    }

    public void backToIndex(@Nullable View view) {
        selectedPage = "index";
        goToOtherPage();
    }

    public void goToOtherPage() {
        this.destoryVlcPlayers();
        webView.loadUrl("http://" + centerServerIp + ":8094/#/" + selectedPage);
//    webView.loadUrl("https://www.babylonjs-playground.com/#WGZLGJ");
    }

    private void clearOldStreamPlayer(Map<String, Object> vlcPlayerMap) {
        if (vlcPlayerMap == null) {
            return;
        }
        VLCPlayer vlcPlayer = (VLCPlayer) vlcPlayerMap.get("player");
        if (vlcPlayer != null) {
            vlcPlayer.release();
            vlcPlayer = null;
        }
        ZoomView relativeLayout = (ZoomView) vlcPlayerMap.get("relativeLayout");
        relativeLayout.stopController();
        if (relativeLayout != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    fatherRelativeLayout.removeView(relativeLayout);
                }
            });

        }
    }


    private void drawVideoList() {
        if (videoMapList == null) {
            return;
        }
        for (int i = 0; i < videoMapList.size(); i++) {
//            创建vlc播放控件
            initVLCPlayer(i);
        }

    }


    private void initVLCPlayer(int i) {
        Map<String, Object> videoMap = videoMapList.get(i);
        Object needDraw = videoMap.get("needDraw");
        if (needDraw != null && (Boolean) needDraw) {
            String streamVariable = conditionMap.get(videoMap.get("streamVariable"));
            if (streamVariable == null || streamVariable.trim().equals("")) {
                return;
            }
            String realStream = streamVariable.trim();
            Map<String, Object> vlcPlayerMap = new HashMap<>();
            double videoWidth = Double.parseDouble(String.valueOf(videoMap.get("w")));
            double videoHeight = Double.parseDouble(String.valueOf(videoMap.get("h")));
            double videoLeft = Double.parseDouble(String.valueOf(videoMap.get("x")));
            double videoTop = Double.parseDouble(String.valueOf(videoMap.get("y")));

            TextureView textureView = new TextureView(this);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT
            );
            textureView.setLayoutParams(params);
            MainActivity.textureView = textureView;
            int realDpWidth = (int) ((videoWidth / webWinWidth) * androidAppWidth);
            int realDpHeight = (int) ((videoHeight / webWinHeight) * androidAppHeight);
            int realDpLeft = (int) ((videoLeft / webWinWidth) * androidAppWidth);
            int realDpTop = (int) ((videoTop / webWinHeight) * androidAppHeight);

            ZoomView relativeLayout = new ZoomView(this, this, realDpWidth, realDpHeight, realStream);


            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(realDpWidth, realDpHeight);
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
            marginLayoutParams.setMargins(realDpLeft, realDpTop, 0, 0);
            relativeLayout.setLayoutParams(layoutParams);
            relativeLayout.setBackgroundColor(Color.BLACK);

            relativeLayout.addView(textureView);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    fatherRelativeLayout.addView(relativeLayout);
                }
            });
            vlcPlayerMap.put("w", videoMap.get("w"));
            vlcPlayerMap.put("h", videoMap.get("h"));
            vlcPlayerMap.put("x", videoMap.get("x"));
            vlcPlayerMap.put("y", videoMap.get("y"));

            vlcPlayerMap.put("relativeLayout", relativeLayout);
            relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    webView.callHandler("videoClickCommand", new Object[]{i}, null);
                }
            });


            textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
                @Override
                public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int otherI, int otherJ) {


                    if (realStream == null || realStream.equals("") || realStream.length() == 0) {
                        return;
                    }
                    VLCPlayer player = (VLCPlayer) vlcPlayerMap.get("player");
                    player = new VLCPlayer(MainActivity.this);
                    player.setVideoSurface(textureView);
                    player.setDataSource(realStream);
                    player.setIndex(i);
                    player.setCallback(MainActivity.this);
                    player.play();
                    vlcPlayerMap.put("player", player);
                    vlcPlayerMap.put("realStreamUrl", realStream);

                }

                @Override
                public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

                }

                @Override
                public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
                    return false;
                }

                @Override
                public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

                }
            });
            oldVlcPlayersMap.put(i, vlcPlayerMap);
        }
    }

    @Override
    protected void onDestroy() {
        destoryVlcPlayers();

        DWebView webView = findViewById(R.id.webView);
        String userAgent = webView.getSettings().getUserAgentString();
        Log.d("WebViewUserAgent", userAgent);
        webView.clearCache(true);
        webView.clearHistory();
        webView.clearFormData();
        webView.destroy();
        webView = null;
        super.onDestroy();
    }

    public void goBack() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "请先启动RemoteController", Toast.LENGTH_SHORT).show();
            }
        });

//        finish(); // 结束当前Activity，返回到上一个Activity
    }

    @Override
    public void onBuffering(float bufferPercent, Integer index) {
        if (bufferPercent >= 100) {
            Map vlcPlayerMap = oldVlcPlayersMap.get(index);
            vlcPlayerMap.put("reTry", 0);
            System.out.println(vlcPlayerMap);
        }
    }

    @Override
    public void onEndReached(Integer index) {

        Map vlcPlayerMap = oldVlcPlayersMap.get(index);

        VLCPlayer player = (VLCPlayer) vlcPlayerMap.get("player");
        Object reTryObject = vlcPlayerMap.get("reTry");
        Integer reTry = null;
        if (reTryObject == null) {
            vlcPlayerMap.put("reTry", 0);
            reTry = 0;
        } else {
            reTry = Integer.parseInt(reTryObject.toString());
        }
        if (player != null) {
            player.release();
            player = null;
        }
        if (reTry == 3) {
            reTry = 0;
            return;
        }
        player = new VLCPlayer(this);

        ZoomView relativeLayout = (ZoomView) vlcPlayerMap.get("relativeLayout");
        TextureView textureView = (TextureView) relativeLayout.getChildAt(0);
        player.setVideoSurface(textureView);
        player.setIndex(index);
        player.setDataSource(vlcPlayerMap.get("realStreamUrl").toString());
        player.setCallback(this);
        player.play();
        vlcPlayerMap.put("reTry", ++reTry);
        Toast.makeText(this, "序列" + index + "播放结束,重试", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onError(Integer index) {

    }

    @Override
    public void onTimeChanged(long currentTime) {

    }

    @Override
    public void onPositionChanged(float position) {

    }

    public void getAppData(String data) {

        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(data, Map.class);
//
        System.out.println(map);
        conditionMap = (Map<String, String>) map.get("dataList");
        webWinWidth = Double.parseDouble(String.valueOf(map.get("webWidth")));
        webWinHeight = Double.parseDouble(String.valueOf(map.get("webHeight")));
        videoMapList = (List<Map<String, Object>>) map.get("videoList");
        checkVlcPlayers();
        drawVideoList();
    }
}
